package com.example.http.demo.service.impl;

import com.example.http.demo.dto.SaveApiKeyDTO;
import com.example.http.demo.dto.UpdateApiKeyDTO;
import com.example.http.demo.model.TblApiKey;
import com.example.http.demo.service.ApiKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Service
public class ApiKeyServiceImpl implements ApiKeyService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void saveApiKey(SaveApiKeyDTO saveApiKeyDTO) {
        final TblApiKey tblApiKey = new TblApiKey();
        tblApiKey.setApiKey(saveApiKeyDTO.getApiKey());
        tblApiKey.setCreateTime(new Date());
        tblApiKey.setCreateUser("system");
        tblApiKey.setRefreshTime(saveApiKeyDTO.getRefreshTime());
        LocalDateTime localDateTime = LocalDateTime.now();
        tblApiKey.setExpireTime(new Date(
                localDateTime.plus(60 * 60, ChronoUnit.SECONDS).getSecond() * 1000));
        tblApiKey.setIsDeleted(0);
        this.redisTemplate.opsForValue().set("api_ticket", tblApiKey, Duration.ofSeconds(1 * 60 * 60L));
    }


    @Override
    public void updateApiKey(UpdateApiKeyDTO updateApiKeyDTO) {
        Object val = this.redisTemplate.opsForValue().get("api_ticket");
        if (val == null) {
            return;
        }
        TblApiKey tblApiKey = (TblApiKey) val;
        final TblApiKey updateEntity = new TblApiKey();
        updateEntity.setApiKey(updateApiKeyDTO.getApiKey());
        updateEntity.setCreateUser(tblApiKey.getCreateUser());
        updateEntity.setCreateTime(tblApiKey.getCreateTime());
        updateEntity.setRefreshTime(new Date());
        updateEntity.setApiCode(tblApiKey.getApiCode());
        updateEntity.setUpdateTime(new Date());
        updateEntity.setUpdateUser("system");
        updateEntity.setIsDeleted(0);
        updateEntity.setId(tblApiKey.getId());
        LocalDateTime localDateTime = LocalDateTime.now();
        updateEntity.setExpireTime(new Date(
                localDateTime.plus(60 * 60, ChronoUnit.SECONDS).getSecond() * 1000));
        this.redisTemplate.opsForValue().set("api_ticket", updateEntity, Duration.ofHours(1));
    }

    @Override
    public TblApiKey selectApiKey() {
        return (TblApiKey) redisTemplate.opsForValue().get("api_ticket");
    }
}
